package com.one.group.admin.excel;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.one.group.model.dto.AdvertData;
import com.one.group.service.AdvertService;
import lombok.extern.slf4j.Slf4j;

import java.util.*;

@Slf4j
public class AdvertDataReadListener implements ReadListener<AdvertData> {

    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 100;

    /**
     * 缓存的数据
     */
    private List<AdvertData> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT); // 存储解析的数据

    // 广告的服务
    private AdvertService advertService;

    // 小区的id
    private Long cellId;

    public AdvertDataReadListener(AdvertService advertService, Long cellId) {
        this.advertService = advertService;
        this.cellId = cellId;
    }

    @Override
    public void invoke(AdvertData data, AnalysisContext context){
        cachedDataList.add(data);

        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }

    }

    // 所有数据解析完成后执行（可选，如批量保存等）
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 可在此处将 dataList 批量插入数据库或进一步处理
        saveData();
        log.info("所有数据解析完成！");
    }

    // 缓存数据的方法
    private void saveData() {
        log.info("{}条数据，开始存储数据库！", cachedDataList.size());

        // 获取小区的id

        cachedDataList.stream().filter(data -> !ObjectUtil.isEmpty(data)).forEach(data -> {
            data.setCellId(cellId);
            advertService.insertAdvertByUpload(data);
        });

        log.info("存储数据库成功！");
    }

}